package oa.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;

import oa.entity.Department;
import oa.entity.User;
import oa.service.UserService;
import oa.service.impl.DepartmentServiceImpl;
import oa.service.impl.UserServiceImpl;

/**
 * Servlet implementation class DeptServlet
 */
@WebServlet("/deptservlet")
public class DeptServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DeptServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String dept = request.getParameter("dept");
		DepartmentServiceImpl deptimpl = new DepartmentServiceImpl();
		UserService userim = new UserServiceImpl();
		User us = new User();
		boolean flag = false;
		boolean yanzheng = false;
		if ("deptadd".equals(dept)) {
			Department department = new Department();
			try {
				String deptname = request.getParameter("val-name");
				String deptPrincipal = request.getParameter("val-principal");
				String companyid = request.getParameter("val-company");
				String deptphone = request.getParameter("val-phone");
				String deptdeptBlurb = request.getParameter("val-deptBlurb");
				if (deptPrincipal == null) {
					deptPrincipal = "0";
				}
				// 根据员工的id更新它的权限
				us.setUserCompetence(1);
				us.setUserId(Integer.parseInt(deptPrincipal));
				yanzheng = userim.updateUserFuZe(us);
				if (yanzheng == true) {
					department.setDeptName(deptname);
					department.setDeptPhone(deptphone);
					department.setDeptPrincipal(Integer.parseInt(deptPrincipal));
					department.setDeptBlurb(deptdeptBlurb);
					department.setCompanyId(Integer.parseInt(companyid));
					flag = deptimpl.addDepartment(department);
				} else {
					flag = false;
				}
				out.print(JSON.toJSONString(flag));
			} catch (Exception e) {
				// TODO: handle exception
			}
			out.flush();
			out.close();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
